<template>
  <view class="home-container">
    <!-- 简化的导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <text class="nav-title">万科门窗ERP</text>
        <view class="nav-right">
          <text class="cuIcon-notification"></text>
        </view>
      </view>
    </view>

    <!-- 用户信息卡片 -->
    <view class="user-card margin-top bg-white padding">
      <view class="flex align-center">
        <image
          :src="userInfo.avatar || '/static/images/default-avatar.png'"
          class="cu-avatar xl round margin-right"
        ></image>
        <view class="flex-sub">
          <view class="text-lg text-bold">{{
            userInfo.empName || "未知用户"
          }}</view>
          <view class="text-sm text-gray margin-top-xs">
            {{ userInfo.departName || "未分配部门" }}
          </view>
        </view>
      </view>
    </view>

    <!-- WMS统计区域 -->
    <view v-if="isDepartment('仓储部')" class="wms-statistics-section margin-top" :style="[{ animation: 'show 0.4s 1' }]">
      <view class="cu-bar bg-white solid-bottom">
        <view class="action">
          <text class="cuIcon-title text-green"></text>WMS统计
        </view>
      </view>
      <view class="statistics-container">
        <WmsStatisticsCard 
          v-for="(card, index) in wmsStatistics" 
          :key="index"
          :data="card"
          @click="handleStatisticsClick"
        />
      </view>
    </view>

    <!-- 生产模块功能 -->
    <view
      class="production-modules bg-white margin-top"
      v-if="isDepartment('生产部')"
    >
      <!-- 生产员工视图 -->
      <view
        v-if="isProductionEmployee && !isProductionAdmin"
        class="production-employee-view"
      >
        <!-- 日期筛选 -->
        <view class="date-filter margin-top bg-white">
          <view class="padding">
            <view class="flex align-center justify-between">
              <text class="text-lg text-bold">数据统计</text>
              <view class="date-range-picker-wrapper">
                <view class="date-range-display flex align-center">
                  <picker
                    mode="date"
                    :value="dateRange.startDate"
                    @change="onStartDateChange"
                  >
                    <view class="date-picker-item flex align-center">
                      <text class="text-blue">{{ dateRange.startDate }}</text>
                      <text
                        class="cuIcon-calendar text-blue margin-left-xs"
                      ></text>
                    </view>
                  </picker>
                  <text class="date-separator margin-lr-sm text-gray">至</text>
                  <picker
                    mode="date"
                    :value="dateRange.endDate"
                    @change="onEndDateChange"
                  >
                    <view class="date-picker-item flex align-center">
                      <text class="text-blue">{{ dateRange.endDate }}</text>
                      <text
                        class="cuIcon-calendar text-blue margin-left-xs"
                      ></text>
                    </view>
                  </picker>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 工作统计 -->
        <view class="work-stats margin-top bg-white">
          <view class="padding-sm">
            <text class="text-lg text-bold">工作统计</text>
          </view>
          <view class="stats-grid grid col-2 padding-sm">
            <view
              v-for="stat in workStats"
              :key="stat.label"
              class="stat-item text-center padding-sm"
            >
              <view
                class="stat-number text-xxl text-bold"
                :style="{ color: stat.color }"
              >
                {{ stat.value }}
              </view>
              <view class="stat-label text-sm text-gray margin-top-xs">
                {{ stat.label }}
              </view>
            </view>
          </view>
        </view>

        <!-- 薪资统计 -->
        <view class="salary-stats margin-top bg-white">
          <view class="section-header padding-lr padding-tb-sm">
            <text class="text-lg text-bold">薪资统计</text>
            <text class="text-sm text-gray margin-left-sm"
              >({{ dateRange.startDate }} 至 {{ dateRange.endDate }})</text
            >
          </view>
          <view class="salary-overview padding">
            <view class="salary-cards grid col-2 gap-sm">
              <view class="salary-card bg-gradual-red shadow-lg">
                <view class="salary-content padding">
                  <view class="salary-icon-wrapper">
                    <text class="cuIcon-money salary-icon"></text>
                  </view>
                  <view class="salary-info">
                    <view class="salary-amount text-white text-xxl text-bold">
                      ¥{{ (salaryStats.totalSalary || 0).toFixed(2) }}
                    </view>
                    <view class="salary-label text-white opacity-8"
                      >总薪资</view
                    >
                  </view>
                </view>
              </view>
              <view class="salary-card bg-gradual-blue shadow-lg">
                <view class="salary-content padding">
                  <view class="salary-icon-wrapper">
                    <text class="cuIcon-list salary-icon"></text>
                  </view>
                  <view class="salary-info">
                    <view class="salary-amount text-white text-xxl text-bold">
                      {{ salaryStats.taskCount || 0 }}
                    </view>
                    <view class="salary-label text-white opacity-8"
                      >执行任务数</view
                    >
                  </view>
                </view>
              </view>
            </view>
            <!-- 平均薪资显示 -->
            <view
              class="avg-salary-info margin-top-sm padding-sm bg-light radius"
            >
              <view class="flex align-center justify-center">
                <text class="text-sm text-gray">平均每任务薪资：</text>
                <text class="text-df text-bold text-blue margin-left-xs">
                  ¥{{
                    salaryStats.taskCount > 0
                      ? (
                          (salaryStats.totalSalary || 0) / salaryStats.taskCount
                        ).toFixed(2)
                      : "0.00"
                  }}
                </text>
              </view>
            </view>
          </view>

          <!-- 任务记录列表 -->
          <view class="task-records">
            <view class="records-header padding-lr">
              <text class="text-df text-bold">执行任务记录</text>
            </view>
            <view class="records-list">
              <view
                v-for="(task, index) in taskRecords"
                :key="task.id"
                class="task-record-item"
                @tap="toggleTaskDetail(index)"
              >
                <view class="record-main padding">
                  <view class="flex align-center justify-between">
                    <view class="task-basic-info flex-sub">
                      <view class="task-name text-bold"
                        >{{ task.id }}-{{ task.workTypeName }}</view
                      >

                      <view
                        class="product-info text-sm text-gray margin-top-xs"
                      >
                        {{ task.productInfo }}
                      </view>
                    </view>
                    <view class="task-salary text-red text-bold">
                      ¥{{ task.salary }}
                    </view>
                    <view class="expand-icon margin-left-sm">
                      <text
                        :class="[
                          'cuIcon-unfold',
                          task.isExpanded ? 'rotate' : '',
                        ]"
                      ></text>
                    </view>
                  </view>
                </view>

                <!-- 折叠详情 -->
                <view
                  v-if="task.isExpanded"
                  class="task-detail-expanded bg-light"
                >
                  <view class="detail-content padding">
                    <view class="detail-row">
                      <text class="detail-label">订单编号：</text>
                      <text class="detail-value">{{ task.orderNo }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">任务状态：</text>
                      <text
                        :class="[
                          'detail-value',
                          getTaskStatusClass(task.status),
                        ]"
                      >
                        {{ getTaskStatusText(task.status) }}
                      </text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">开始时间：</text>
                      <text class="detail-value">{{ task.claimedTime }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">完成时间：</text>
                      <text class="detail-value">{{ task.endTime }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">计件单价：</text>
                      <text class="detail-value">¥{{ task.unitPrice }}</text>
                    </view>
                    <view class="detail-row">
                      <text class="detail-label">完成数量：</text>
                      <text class="detail-value">{{
                        task.completedQuantity
                      }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 生产管理员视图 -->
      <view v-if="isProductionAdmin" class="production-admin-view">
        <!-- 生产概览统计 -->
        <view class="overview-stats margin-top">
          <view class="overview-card bg-white">
            <view class="overview-header padding">
              <text class="text-lg text-bold">生产概览</text>
              <text class="text-sm text-gray">{{ todayDate }}</text>
            </view>
            <view class="overview-content padding">
              <view class="overview-row">
                <view class="overview-item">
                  <view class="overview-number text-blue">{{
                    productionStats.totalPlans
                  }}</view>
                  <view class="overview-label">生产计划</view>
                </view>
                <view class="overview-item">
                  <view class="overview-number text-green">{{
                    productionStats.completedPlans
                  }}</view>
                  <view class="overview-label">已完成</view>
                </view>
                <view class="overview-item">
                  <view class="overview-number text-orange">{{
                    productionStats.inProgressPlans
                  }}</view>
                  <view class="overview-label">进行中</view>
                </view>
                <view class="overview-item">
                  <view class="overview-number text-red">{{
                    productionStats.delayedPlans
                  }}</view>
                  <view class="overview-label">延期</view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 员工任务分布 -->
        <view class="task-distribution margin-top bg-white">
          <view class="section-title padding">
            <text class="text-lg text-bold">员工任务分布</text>
          </view>
          <view class="distribution-content padding">
            <view class="distribution-row">
              <view class="distribution-item">
                <view class="distribution-icon bg-blue">
                  <text class="cuIcon-people text-white"></text>
                </view>
                <view class="distribution-info">
                  <view class="distribution-number">{{
                    employeeStats.totalEmployees
                  }}</view>
                  <view class="distribution-label">在岗员工</view>
                </view>
              </view>
              <view class="distribution-item">
                <view class="distribution-icon bg-green">
                  <text class="cuIcon-play text-white"></text>
                </view>
                <view class="distribution-info">
                  <view class="distribution-number">{{
                    employeeStats.workingEmployees
                  }}</view>
                  <view class="distribution-label">工作中</view>
                </view>
              </view>
              <view class="distribution-item">
                <view class="distribution-icon bg-orange">
                  <text class="cuIcon-pause text-white"></text>
                </view>
                <view class="distribution-info">
                  <view class="distribution-number">{{
                    employeeStats.idleEmployees
                  }}</view>
                  <view class="distribution-label">空闲</view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 管理员快捷操作 -->
        <view class="admin-actions margin-top bg-white">
          <view class="section-title padding">
            <text class="text-lg text-bold">管理操作</text>
          </view>
          <view class="admin-action-grid padding">
            <view class="action-item" @click="goToProductionPlan">
              <view class="action-icon bg-blue">
                <text class="cuIcon-calendar text-white"></text>
              </view>
              <text class="action-label">生产计划</text>
            </view>
            <view class="action-item" @click="goToTaskManagement">
              <view class="action-icon bg-green">
                <text class="cuIcon-list text-white"></text>
              </view>
              <text class="action-label">任务管理</text>
            </view>
            <view class="action-item" @click="goToEmployeeManagement">
              <view class="action-icon bg-purple">
                <text class="cuIcon-group text-white"></text>
              </view>
              <text class="action-label">员工管理</text>
            </view>
            <view class="action-item" @click="goToQualityManagement">
              <view class="action-icon bg-orange">
                <text class="cuIcon-check text-white"></text>
              </view>
              <text class="action-label">质量管理</text>
            </view>
            <view class="action-item" @click="goToProductionReport">
              <view class="action-icon bg-cyan">
                <text class="cuIcon-form text-white"></text>
              </view>
              <text class="action-label">生产报表</text>
            </view>
            <view class="action-item" @click="goToExceptionManagement">
              <view class="action-icon bg-red">
                <text class="cuIcon-warn text-white"></text>
              </view>
              <text class="action-label">异常处理</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    </view>
  </view>
</template>

<script>
import salaryApi from "@/api/mes/salary.js";
import taskApi from "@/api/mes/task.js";
import { USER_INFO } from "@/common/util/constants.js";
import WmsStatisticsCard from "@/components/wms/WmsStatisticsCard.vue";

export default {
  components: {
    WmsStatisticsCard,
  },
  data() {
    return {
      userInfo: {},
      // 生产员工数据
      dateRange: {
        startDate: this.formatDate(new Date()),
        endDate: this.formatDate(new Date()),
      },
      salaryStats: {
        totalSalary: 0,
        taskCount: 0,
      },
      taskRecords: [],
      workStatistics: {
        completedTasks: 0,
        ongoingTasks: 0,
      },
      // 生产管理员数据
      productionStats: {
        totalPlans: 0,
        completedPlans: 0,
        inProgressPlans: 0,
        delayedPlans: 0,
      },
      employeeStats: {
        totalEmployees: 0,
        workingEmployees: 0,
        idleEmployees: 0,
      },
      // WMS统计数据
      wmsStatistics: [
        {
          icon: "📦",
          title: "物料业务统计",
          clickable: true,
          page: "wmsMaterialBusiness",
          items: [
            {
              key: "materialInbound",
              label: "物料入库单总数",
              value: "0",
              alertClass: "normal",
            },
            {
              key: "materialOutbound",
              label: "物料出库单总数",
              value: "0",
              alertClass: "normal",
            },
          ],
        },
        {
          icon: "📊",
          title: "成品业务统计",
          clickable: true,
          page: "wmsFinishedGoodsBusiness",
          items: [
            {
              key: "finishedInbound",
              label: "成品入库单总数",
              value: "0",
              alertClass: "normal",
            },
            {
              key: "finishedOutbound",
              label: "成品出库单总数",
              value: "0",
              alertClass: "normal",
            },
          ],
        },
      ],
    };
  },

  computed: {
    // 判断是否为管理员
    isManager() {
      const loginType = uni.getStorageSync("erp_login_type");
      return loginType == "admin" || loginType == "manager";
    },

    // 判断是否为生产管理员
    isProductionAdmin() {
      return this.isDepartment("生产部") && this.isManager;
    },

    // 判断是否为生产员工
    isProductionEmployee() {
      return this.isDepartment("生产部") && !this.isManager;
    },

    // 计算工作统计数据
    workStats() {
      return [
        {
          label: "已完成任务",
          value: this.workStatistics.completedTasks,
          color: "#52c41a",
        },
        {
          label: "正在进行任务",
          value: this.workStatistics.ongoingTasks,
          color: "#1890ff",
        },
      ];
    },
  },

  onLoad() {
    this.initPage();
  },

  onShow() {
    this.refreshData();
  },

  methods: {
    // WMS统计卡片点击处理
    handleStatisticsClick(cardData) {
      console.log("WMS统计卡片点击:", cardData);
      if (cardData.page) {
        uni.showToast({
          title: `跳转到${cardData.title}详情页`,
          icon: "none",
        });
        // 后续可以根据具体页面配置进行跳转
        // this.$Router.push({ name: cardData.page });
      }
    },

    async initPage() {
      console.log("首页初始化开始");
      this.loadUserInfo();
      console.log("用户信息加载完成:", this.userInfo);

      // 等待下一个tick确保数据已更新
      await this.$nextTick();

      this.initProductionData();
      
      // 如果是仓储部用户，加载WMS统计数据
      if (this.isDepartment('仓储部')) {
        this.loadWmsStatistics();
      }
      
      console.log("首页数据加载完成", this.userInfo);
    },

    loadUserInfo() {
      const userInfo = uni.getStorageSync(USER_INFO) || {};
      console.log("从存储获取的用户信息:", userInfo);

      // 如果用户信息为空，尝试从其他地方获取或使用测试数据
      if (!userInfo.id) {
        console.log("用户信息为空，尝试获取当前登录用户信息");

        // 尝试从全局状态或其他存储获取
        const altUserInfo =
          uni.getStorageSync("userInfo") ||
          uni.getStorageSync("user_info") ||
          {};
        console.log("备用用户信息:", altUserInfo);

        if (altUserInfo.id) {
          this.userInfo = altUserInfo;
        } else {
          // 使用测试数据（开发环境）
          console.warn("未找到用户信息，使用测试数据");
          this.userInfo = {
            id: "1863435939312185600", // 使用API请求中的employeeId
            empName: "测试用户",
            departName: "生产部",
          };
        }
      } else {
        this.userInfo = userInfo;
      }

      console.log("最终用户信息:", this.userInfo);
    },

    // 初始化生产模块数据
    initProductionData() {
      if (this.isDepartment("生产部")) {
        if (!this.isManager) {
          this.loadEmployeeProductionData();
        } else {
          this.loadAdminProductionData();
        }
      }
    },

    // 加载员工生产数据
    async loadEmployeeProductionData() {
      try {
        console.log("开始加载员工生产数据，用户信息:", this.userInfo);

        // 确保用户信息已加载
        if (!this.userInfo.id) {
          console.log("用户信息未加载，重新加载用户信息...");
          this.loadUserInfo();
          await this.$nextTick();

          if (!this.userInfo.id) {
            console.error("用户信息仍为空，无法加载数据");
            return;
          }
        }

        await Promise.all([
          this.loadSalaryStatistics(),
          this.loadTaskRecords(),
          this.loadWorkStatistics(),
        ]);

        console.log("员工生产数据加载完成，薪资统计:", this.salaryStats);
      } catch (error) {
        console.error("加载生产数据失败:", error);
        uni.showToast({
          title: "数据加载失败",
          icon: "none",
        });
      }
    },

    // 加载薪资统计
    async loadSalaryStatistics() {
      try {
        console.log("加载薪资统计 - 用户信息:", this.userInfo);
        console.log("加载薪资统计 - 日期范围:", this.dateRange);

        if (!this.userInfo.id) {
          console.error("用户ID为空，无法加载薪资统计");
          return;
        }

        // 使用日期范围一次性获取薪资统计
        const response = await salaryApi.getRangeSalary({
          employeeId: this.userInfo.id,
          startDate: this.dateRange.startDate,
          endDate: this.dateRange.endDate,
        });
        //实际数据在response.data.result中

        console.log("薪资统计API响应:", response);

        if (response.data.success && response.data.result) {
          this.salaryStats = {
            totalSalary: response.data.result.totalSalary || 0,
            taskCount: response.data.result.taskCount || 0,
          };
          console.log("薪资统计数据更新成功:", this.salaryStats);
        } else {
          this.salaryStats = {
            totalSalary: 0,
            taskCount: 0,
          };
          console.log("薪资统计API响应失败，使用默认值");
        }

        // 强制触发页面更新
        this.$forceUpdate();
      } catch (error) {
        console.error("加载薪资统计失败:", error);
        // 设置默认值
        this.salaryStats = {
          totalSalary: 0,
          taskCount: 0,
        };
      }
    },

    // 加载任务记录
    async loadTaskRecords() {
      try {
        console.log("开始加载任务参与记录，用户ID:", this.userInfo.id);

        const response = await taskApi.listByEmpIdAndSubmitStatus({
          employeeId: this.userInfo.id,
          startDate: this.dateRange.startDate,
          endDate: this.dateRange.endDate,
          pageNo: 1,
          pageSize: 20,
        });

        console.log("任务参与记录API响应:", response);

        if (
          response.data.success &&
          response.data.result &&
          response.data.result.records
        ) {
          // 过滤只返回已执行完成的任务记录
          const completedTasks = response.data.result.records.filter(
            (participant) => {
              // 判断任务参与状态是否为已完成
              // 假设状态值：0-待开始，1-进行中，2-已完成，3-已暂停
              return participant.status === 2 || participant.status === "2";
            }
          );

          console.log("已完成的任务记录数量:", completedTasks.length);

          this.taskRecords = completedTasks.map((participant) => ({
            ...participant,
            isExpanded: false, // 添加展开状态
            // 格式化显示字段
            taskName:
              participant.taskName || participant.workTypeName || "未知任务",
            productInfo:
              participant.productInfo || participant.productName || "未知产品",
            salary: (
              participant.unitPrice * participant.completedQuantity || 0
            ).toFixed(2), // 显示参与者的薪资  unitPirce * completedQuantity
            status: this.getTaskStatusFromNumber(participant.status),
            completedQuantity: participant.completedQuantity || 0,
          }));
        } else {
          this.taskRecords = [];
        }
      } catch (error) {
        this.taskRecords = [];
      }
    },

    // 加载工作统计
    async loadWorkStatistics() {
      try {
        const response = await taskApi.getEmployeeWorkStatistics({
          employeeId: this.userInfo.id,
          startDate: this.dateRange.startDate,
          endDate: this.dateRange.endDate,
        });
        console.log("工作统计API响应:", response);
        if (response.data.success && response.data.result) {
          this.workStatistics = {
            completedTasks: response.data.result.completedTasks || 0,
            ongoingTasks: response.data.result.ongoingTasks || 0,
          };
        } else {
          this.workStatistics = {
            completedTasks: 0,
            ongoingTasks: 0,
          };
        }
      } catch (error) {
        console.error("加载工作统计失败:", error);
        this.workStatistics = {
          completedTasks: 0,
          ongoingTasks: 0,
        };
      }
    },

    // 开始日期变更处理
    onStartDateChange(e) {
      this.dateRange.startDate = e.detail.value;
      // 确保开始日期不晚于结束日期
      if (this.dateRange.startDate > this.dateRange.endDate) {
        this.dateRange.endDate = this.dateRange.startDate;
      }
      this.loadEmployeeProductionData();
    },

    // 结束日期变更处理
    onEndDateChange(e) {
      this.dateRange.endDate = e.detail.value;
      // 确保结束日期不早于开始日期
      if (this.dateRange.endDate < this.dateRange.startDate) {
        this.dateRange.startDate = this.dateRange.endDate;
      }
      this.loadEmployeeProductionData();
    },

    // 切换任务记录展开状态
    toggleTaskRecord(taskId) {
      const task = this.taskRecords.find((t) => t.id === taskId);
      if (task) {
        task.isExpanded = !task.isExpanded;
      }
    },

    // 格式化日期
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 格式化时间
    formatTime(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${hours}:${minutes}`;
    },

    // 获取任务状态样式类
    getTaskStatusClass(status) {
      const statusMap = {
        pending: "text-orange",
        in_progress: "text-blue",
        completed: "text-green",
        paused: "text-gray",
      };
      return statusMap[status] || "text-gray";
    },

    // 获取任务状态文本
    getTaskStatusText(status) {
      const statusMap = {
        pending: "待开始",
        in_progress: "进行中",
        completed: "已完成",
        paused: "已暂停",
      };
      return statusMap[status] || "未知";
    },

    // 将数字状态转换为字符串状态
    getTaskStatusFromNumber(statusNum) {
      const statusMap = {
        0: "pending", // 待开始
        1: "in_progress", // 进行中
        2: "completed", // 已完成
        3: "paused", // 已暂停
      };
      return statusMap[statusNum] || "pending";
    },

    // 加载管理员生产数据
    async loadAdminProductionData() {
      try {
        // TODO: 实现实际的API调用
        // 临时模拟数据
        this.productionStats = {
          totalPlans: 25,
          completedPlans: 18,
          inProgressPlans: 5,
          delayedPlans: 2,
        };

        this.employeeStats = {
          totalEmployees: 32,
          workingEmployees: 28,
          idleEmployees: 4,
        };
      } catch (error) {
        console.error("加载管理员数据失败:", error);
      }
    },

    // 判断是否为指定部门
    isDepartment(departName) {
      return this.userInfo.departName == departName;
    },

    refreshData() {
      this.loadEmployeeProductionData();
      // 如果是仓储部用户，刷新WMS统计数据
      if (this.isDepartment('仓储部')) {
        this.loadWmsStatistics();
      }
    },

    // 加载WMS统计数据
    async loadWmsStatistics() {
      try {
        console.log("开始加载WMS统计数据");
        
        // 并行请求物料和成品业务统计
        const [materialStats, finishedStats] = await Promise.all([
          this.$http.get("/wms/inboundOrder/statistics/business"),
          this.$http.get("/wms/finished-goods/inventory/statistics/business")
        ]);

        console.log("物料统计数据:", materialStats);
        console.log("成品统计数据:", finishedStats);

        // 更新物料业务统计
        if (materialStats.data && materialStats.data.success) {
          const materialData = materialStats.data.result;
          this.wmsStatistics[0].items[0].value = materialData.materialInboundCount || 0;
          this.wmsStatistics[0].items[1].value = materialData.materialOutboundCount || 0;
        }

        // 更新成品业务统计
        if (finishedStats.data && finishedStats.data.success) {
          const finishedData = finishedStats.data.result;
          this.wmsStatistics[1].items[0].value = finishedData.finishedInboundCount || 0;
          this.wmsStatistics[1].items[1].value = finishedData.finishedOutboundCount || 0;
        }

        console.log("WMS统计数据加载完成");
      } catch (error) {
        console.error("加载WMS统计数据失败:", error);
        // 发生错误时显示提示，但不影响页面正常使用
        uni.showToast({
          title: "统计数据加载失败",
          icon: "none",
          duration: 2000
        });
      }
    },

    // 切换任务详情展开/收起
    toggleTaskDetail(index) {
      if (this.taskRecords[index]) {
        this.taskRecords[index].isExpanded =
          !this.taskRecords[index].isExpanded;
        this.$forceUpdate(); // 强制更新视图
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.home-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-top: var(--status-bar-height);

  .nav-content {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 32rpx;

    .nav-title {
      font-size: 36rpx;
      font-weight: bold;
      color: white;
    }

    .nav-right {
      .cuIcon-notification {
        font-size: 40rpx;
        color: white;
      }
    }
  }
}

.user-card {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;

  .role-badge {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;

    .cuIcon {
      font-size: 36rpx;
      color: white;
    }
  }
}

.quick-actions {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;

  .quick-action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24rpx 12rpx;

    .action-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12rpx;

      .cuIcon {
        font-size: 36rpx;
      }
    }
  }
}

.function-modules {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;

  .module-item {
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .module-icon {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f0f9ff;
      border-radius: 12rpx;

      .cuIcon {
        font-size: 32rpx;
      }
    }
  }
}

.work-stats {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx 24rpx;

  .stat-item {
    border-radius: 8rpx;
    background-color: #fafafa;
  }
}

// 薪资统计样式
.salary-stats {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;

  .section-header {
    border-bottom: 1rpx solid #f0f0f0;

    .text-gray {
      font-size: 24rpx;
      opacity: 0.8;
    }
  }

  .salary-cards {
    .salary-card {
      border-radius: 16rpx;
      overflow: hidden;
      position: relative;

      .salary-content {
        position: relative;
        z-index: 2;

        .salary-icon-wrapper {
          position: absolute;
          top: 16rpx;
          right: 16rpx;
          opacity: 0.3;

          .salary-icon {
            font-size: 48rpx;
            color: white;
          }
        }

        .salary-info {
          .salary-amount {
            font-size: 48rpx;
            line-height: 1.2;
            margin-bottom: 8rpx;
          }

          .salary-label {
            font-size: 26rpx;
          }
        }
      }
    }
  }

  .avg-salary-info {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: 1rpx solid #dee2e6;
  }
}

// 任务记录样式
.task-records {
  .records-header {
    padding: 24rpx 32rpx 16rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }

  .task-record-item {
    border-bottom: 1rpx solid #f8f9fa;
    transition: all 0.3s ease;

    &:last-child {
      border-bottom: none;
    }

    &:active {
      background-color: #f8f9fa;
    }

    .record-main {
      .expand-icon {
        .cuIcon-unfold {
          font-size: 32rpx;
          color: #999;
          transition: transform 0.3s ease;

          &.rotate {
            transform: rotate(180deg);
          }
        }
      }
    }

    .task-detail-expanded {
      border-top: 1rpx solid #e9ecef;
      animation: slideDown 0.3s ease;

      .detail-content {
        .detail-row {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .detail-label {
            font-size: 28rpx;
            color: #666;
            width: 160rpx;
            flex-shrink: 0;
          }

          .detail-value {
            font-size: 28rpx;
            color: #333;
            flex: 1;

            &.text-green {
              color: #52c41a;
            }

            &.text-blue {
              color: #1890ff;
            }

            &.text-orange {
              color: #fa8c16;
            }

            &.text-red {
              color: #f5222d;
            }
          }
        }
      }
    }
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
  }
  to {
    opacity: 1;
    max-height: 500rpx;
  }
}

// 生产模块样式
.production-modules {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
}

// 日期范围选择器样式
.date-range-picker-wrapper {
  .date-range-display {
    background-color: #f8f9fa;
    border-radius: 8rpx;
    padding: 8rpx 12rpx;

    .date-picker-item {
      padding: 4rpx 8rpx;
      border-radius: 4rpx;
      background-color: white;
      border: 1rpx solid #e9ecef;

      &:hover {
        background-color: #f0f9ff;
      }
    }

    .date-separator {
      font-size: 24rpx;
      color: #6c757d;
    }
  }
}

.stats-cards {
  padding: 0 24rpx;

  .stats-row {
    display: flex;
    gap: 16rpx;
    margin-bottom: 16rpx;

    .stats-card {
      flex: 1;
      padding: 24rpx;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      .stats-icon {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16rpx;

        .cuIcon {
          font-size: 28rpx;
        }
      }

      .stats-info {
        flex: 1;

        .stats-number {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
        }

        .stats-label {
          font-size: 24rpx;
          color: #666;
          margin-top: 4rpx;
        }
      }
    }
  }
}

.quick-actions,
.admin-actions {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;

  .action-grid,
  .admin-action-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 16rpx 8rpx;

      .action-icon {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 8rpx;

        .cuIcon {
          font-size: 28rpx;
        }
      }

      .action-label {
        font-size: 24rpx;
        color: #333;
        text-align: center;
      }
    }
  }
}

.overview-stats {
  padding: 0 24rpx;

  .overview-card {
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

    .overview-header {
      border-bottom: 1rpx solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .overview-row {
      display: flex;
      justify-content: space-around;

      .overview-item {
        text-align: center;

        .overview-number {
          font-size: 32rpx;
          font-weight: bold;
          margin-bottom: 8rpx;
        }

        .overview-label {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
}

.task-distribution {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;

  .distribution-row {
    display: flex;
    justify-content: space-around;

    .distribution-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .distribution-icon {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 12rpx;

        .cuIcon {
          font-size: 28rpx;
        }
      }

      .distribution-info {
        text-align: center;

        .distribution-number {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
        }

        .distribution-label {
          font-size: 24rpx;
          color: #666;
          margin-top: 4rpx;
        }
      }
    }
  }
}

/* WMS统计区域样式 */
.wms-statistics-section {
  margin: 24rpx;
}

.statistics-container {
  padding: 24rpx;
  background: #f5f5f5;
  border-radius: 0 0 16rpx 16rpx;
}
</style>
